import json

from django.shortcuts import render
from django.views import View

from apiwork import models as apiwork_models
from utils.jsonoperator import translate2json
from utils.response_code import ResCode, error_map


class ApiView(View):
    def get(self, request):
        return render(request, 'home/index.html')


class CollectionsView(View):
    def get(self, request):
        # 需要过滤掉没有逻辑删除的
        tags = apiwork_models.Collections.objects.values('id', 'name').filter(is_delete=False).order_by('update_time')
        return render(request, 'home/collections.html', locals())

    def post(self, request):
        post_data = request.body
        if not post_data:
            return translate2json(errno=ResCode.PARAMERR, errmsg=error_map[ResCode.PARAMERR])
        dict_data = json.loads(post_data.decode('utf8'))
        tag_name = dict_data.get('name')
        if tag_name and tag_name.strip():
            tag_instance, tag_created_bolean = apiwork_models.Collections.objects.get_or_create(name=tag_name)
            new_tag_dict = {
                'id': tag_instance.id,
                'name': tag_instance.name
            }
            if tag_created_bolean:
                return translate2json(errno=ResCode.OK, errmsg="接口集创建成功", data=new_tag_dict)
            else:
                return translate2json(errno=ResCode.DATAEXIST, errmsg="接口集名不存在")


class CollectionsEditView(View):
    def put(self, request, collections_id):
        put_data = request.body
        if not put_data:
            return translate2json(errno=ResCode.PARAMERR, errmsg=error_map[ResCode.PARAMERR])
        dict_data = json.loads(put_data.decode('utf8'))
        get_tag_name = dict_data.get('name')
        tag = apiwork_models.Collections.objects.only('id').filter(id=collections_id).first()
        if tag:
            if get_tag_name and get_tag_name.strip():
                if not apiwork_models.Collections.objects.only('id').filter(name=get_tag_name).exists():
                    tag.name = get_tag_name
                    tag.save(update_fields=['name'])
                    return translate2json(errmsg='接口集更新成功')
                else:
                    return translate2json(errno=ResCode.PARAMERR, errmsg="接口集已存在")
            else:
                return translate2json(errno=ResCode.PARAMERR, errmsg="接口集为空")
        else:
            return translate2json(errno=ResCode.PARAMERR, errmsg="需要更新的接口集不存在")

    def delete(self, request, collections_id):
        tag = apiwork_models.Collections.objects.only('id').filter(id=collections_id).first()
        if tag:
            # tag.delete() # 物理删除
            tag.is_delete = True  # 逻辑删除
            tag.save(update_fields=['is_delete'])
            return translate2json(errmsg="标签删除成功")
        else:
            return translate2json(errno=ResCode.PARAMERR, errmsg="此标签不存在")


class ApiAddView(View):
    def get(self, request):
        return render(request, 'home/api_add.html')
